﻿using BaseUtils;
using Service.src.NW.Model;
using System.Web.Http.SelfHost;
using System.Windows.Forms;
using System;
using System.Web.Http.Cors;
using System.Threading.Tasks;
using System.Web.Cors;
using System.Net.Http;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http; // 确保有这个引用

namespace Service.src
{
    public class AppService
    {
        public AppService()
        {
            new BaseService("AppConfig.xml");
            AppData Global = new AppData();
            Global
            .LoadDevice()
                .Heartbeat(false)
                .LoadEvent()
                .UpdatePlcAddress()
                .SetGlobalParams()
                .OpenWebSocket();
            StartWebApiService();
        }

        private HttpSelfHostServer _server;
        private readonly string _baseAddress = "http://127.0.0.1:5123/";

        public void StartWebApiService()
        {
            try
            {
                if (_server == null)
                {
                    var config = new HttpSelfHostConfiguration(_baseAddress);

                    // 配置跨域访问 - 使用扩展方法方式
                    var cors = new EnableCorsAttribute("*", "*", "*");


                    // 在WebApiConfig中配置具体的CORS规则
                    // 或者在这里直接配置
                    // config.SetCorsPolicyProviderFactory(new CorsPolicyProviderFactory());
                    //  config.EnableCors(); // 启用CORS
                    // 关键修复：启用CORS配置
                    config.SetCorsPolicyProviderFactory(new CorsPolicyProviderFactory());
                    config.EnableCors(); // 启用CORS
                    // 增加超时配置（解决长时间请求问题）
                    // config.TransferMode = TransferMode.Streamed;
                    config.SendTimeout = TimeSpan.FromMinutes(5);
                    config.ReceiveTimeout = TimeSpan.FromMinutes(5);

                    // 其他配置保持不变
                    config.MaxReceivedMessageSize = 104857600;
                    config.MaxBufferSize = 104857600;

                    var jsonFormatter = config.Formatters.JsonFormatter;
                    jsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
                    {
                        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                        MaxDepth = 128
                    };

                    WebApiConfig.Register(config);

                    _server = new HttpSelfHostServer(config);
                    _server.OpenAsync().Wait();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动服务失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void StopWebApiService()
        {
            if (_server != null)
            {
                _server.CloseAsync().Wait();
                _server.Dispose();
                _server = null;
            }
        }
    }

    // 新增：CORS策略提供器工厂
    public class CorsPolicyProviderFactory : ICorsPolicyProviderFactory
    {
        private readonly ICorsPolicyProvider _provider = new MyCorsPolicyProvider();


        public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            // 修改：使用安全方式获取Origin头
            string origin = GetOriginFromRequest(request);
            return _provider;
        }

        // 新增：获取请求来源的辅助方法
        private string GetOriginFromRequest(HttpRequestMessage request)
        {
            if (request.Headers.TryGetValues("Origin", out IEnumerable<string> origins))
            {
                return string.Join(",", origins);
            }
            return "未知来源";
        }
    }



    public class MyCorsPolicyProvider : ICorsPolicyProvider
    {
        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var policy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true,
                SupportsCredentials = true,
                PreflightMaxAge = 10
            };

            // 修改：使用TryGetValues获取Origin头
            string origin = null;
            if (request.Headers.TryGetValues("Origin", out IEnumerable<string> origins))
            {
                origin = origins?.FirstOrDefault();
            }

            // 根据来源配置CORS策略
            if (string.IsNullOrEmpty(origin) || origin == "null")
            {
                policy.Origins.Add("null"); // 支持file://协议
            }
            else if (origin.StartsWith("http://app.local"))
            {
                policy.Origins.Add(origin); // 支持WebView2虚拟域名
            }
            else if (origin.StartsWith("http://localhost") || origin.StartsWith("http://127.0.0.1"))
            {
                policy.Origins.Add(origin); // 支持本地开发环境
            }
            else
            {
                policy.Origins.Add("*"); // 开发环境临时允许所有来源
            }

            return Task.FromResult(policy);
        }
    }


    // 新增：自定义CORS策略
    public class MyCorsPolicyProvider2 : ICorsPolicyProvider
    {
        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var policy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true
            };

            // 允许所有来源
            policy.Origins.Add("*");

            // 或者指定允许的来源
            // policy.Origins.Add("http://localhost:3000");
            // policy.Origins.Add("http://example.com");

            return Task.FromResult(policy);
        }
    }
}
